<?php

namespace app\controllers\merchant\live;


use app\models\core\UploadsModel;
use app\models\shop\LiveModel;
use app\models\shop\ShopGoodsModel;
use yii;
use yii\web\MerchantController;
use EasyWeChat\Factory;

/**
 * 仓库
 * @author  wmy
 * Class StorehouseController
 * @package app\controllers\merchant\storehouse
 */
class LiveController extends MerchantController
{

    public $enableCsrfValidation = false; //禁用CSRF令牌验证，可以在基类中设置

    public function behaviors()
    {
        return [
            'token' => [
                'class' => 'yii\filters\MerchantFilter', //调用过滤器
                'except' => ['index','upload'], //指定控制器不应用到哪些动作
            ]
        ];
    }


    /**
     * 查询列表
     * @return array
     * @throws yii\db\Exception
     */
    public function actionList()
    {
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数
            $must = ['type'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            $model = new LiveModel();
            if ($params['type'] == 'wx') {
                $config = $this->getSystemConfig('ccvWPn', 'miniprogram');
                if ($config == false) {
                    return result(500, "未配置小程序信息");
                }
                $miniProgram = Factory::miniProgram($config);
                $token = $miniProgram->access_token->getToken(true); // 强制重新从微信服务器获取 token
                $miniProgram['access_token']->setToken($token['access_token'], 7200);
                $this->live($token['access_token']);
            }
            $where['limit'] = false;
            $array = $model->do_select($where);
            if ($array['status'] == 200){
                foreach ($array['data'] as $k=>$v){
                    $array['data'][$k]['goods'] = json_decode($v['goods'],true);
                }
            }
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    function live($token){
        $url = "https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=" .$token;
        $data = json_encode(['start' => 0, 'limit' => 100]);
        $res = json_decode(curlPost($url, $data), true);
        if ($res['errcode'] == 0) {
            for ($i = 0; $i < count($res['room_info']); $i++) {
                //直播间信息入库
                $model = new LiveModel();
                $where['roomid'] = $res['room_info'][$i]['roomid'];
                $info = $model->do_one($where);
                $liveData = [];
                $liveData['name'] = $res['room_info'][$i]['name'];
                $liveData['cover_img'] = $res['room_info'][$i]['cover_img'];
                $liveData['start_time'] = $res['room_info'][$i]['start_time'];
                $liveData['end_time'] = $res['room_info'][$i]['end_time'];
                $liveData['anchor_name'] = $res['room_info'][$i]['anchor_name'];
                $liveData['share_img'] = $res['room_info'][$i]['share_img'];
                $liveData['goods'] = json_encode($res['room_info'][$i]['goods'],JSON_UNESCAPED_UNICODE);
                $liveData['live_status'] = $res['room_info'][$i]['live_status'];
                $replay = $this->replay($token,$res['room_info'][$i]['roomid']); //获取各直播间的回放源视频
                if ($replay['errcode'] == 0){
                    $liveData['replay'] = json_encode($replay['live_replay'],JSON_UNESCAPED_UNICODE);
                }
                if ($info['status'] == 200) {
                    $model->do_update($where,$liveData);
                } else {
                    $liveData['roomid'] = $res['room_info'][$i]['roomid'];
                    $model->do_add($liveData);
                }
            }
        }
    }

    function replay($token,$roomid){
        $url = "https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=" .$token;
        $data = json_encode(['action'=>'get_replay','room_id'=>$roomid,'start' => 0, 'limit' => 100]);
        $res = json_decode(curlPost($url, $data), true);
        return $res;
    }

    //处理链接图片上传至微信
    function download($url,$token){
        creat_mulu("./uploads/goods/".yii::$app->session['uid']);
        $path = "./uploads/goods/".yii::$app->session['uid'] . "/" . date('Y') . "/" . date('m') . "/" . date('d') . "/";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);

        //图片超过300*300进行压缩处理
        $img = $path . $filename;
        list($width, $height) = getimagesize($img); //获取原图尺寸
        if ($width > 300 || $height > 300){
            if ($width >= $height){
                $percent = 300 / $width; //图片压缩比
            } else {
                $percent = 300 / $height; //图片压缩比
            }
            //缩放尺寸
            $newwidth = $width * $percent;
            $newheight = $height * $percent;
            $src_im = imagecreatefromjpeg($img);
            $dst_im = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresized($dst_im, $src_im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            imagejpeg($dst_im,$img); //输出压缩后的图片
            imagedestroy($dst_im);
            imagedestroy($src_im);
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$token.'&type=image';
        $data = array(
            'media'=>new \CURLFile($img),
        );
        $res = json_decode(curlPost($url, $data), true);
        if (!isset($res['errcode'])) {
            unlink($img);
            return result(200, "请求成功",['media_id'=>$res['media_id']]);
        } else {
            return result(500, $res['errmsg']);
        }
    }

    public function actionUpdate($id){
        if (yii::$app->request->isPut) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参

            $model = new LiveModel();
            if (isset($params['status']) && $params['status'] == 1){
                $model->do_update([],['status'=>0]);
            }
            $array = $model->do_update(['roomid'=>$id],$params);
            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    //创建直播间
    public function actionAdd(){
        if (yii::$app->request->isPost) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参

            $must = ['name','coverImg','startTime','endTime','anchorName','anchorWechat','shareImg','type','screenType','closeLike','closeGoods','closeComment'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }

            $config = $this->getSystemConfig('ccvWPn', 'miniprogram');
            if ($config == false) {
                return result(500, "未配置小程序信息");
            }
            $miniProgram = Factory::miniProgram($config);
            $token = $miniProgram->access_token->getToken(true); // 强制重新从微信服务器获取 token
            $miniProgram['access_token']->setToken($token['access_token'], 7200);

            $url = 'https://api.weixin.qq.com/wxaapi/broadcast/room/create?access_token='.$token['access_token'];

            $data = json_encode([
                'name'=>$params['name'],
                'coverImg'=>$params['coverImg'],
                'startTime'=>$params['startTime'],
                'endTime'=>$params['endTime'],
                'anchorName'=>$params['anchorName'],
                'anchorWechat'=>$params['anchorWechat'],
                'shareImg'=>$params['shareImg'],
                'type'=>$params['type'],
                'screenType'=>$params['screenType'],
                'closeLike'=>$params['closeLike'],
                'closeGoods'=>$params['closeGoods'],
                'closeComment'=>$params['closeComment'],
            ]);
            $res = json_decode(curlPostJson($url, $data), true);

            if ($res['errcode'] == 0) {
                $this->live($token['access_token']);
                return result(200, "请求成功");
            } else {
                return result(500, $res['errmsg']);
            }
        } else {
            return result(500, "请求方式错误");
        }
    }

    //上传图片至微信
    public function actionUpload(){
        if (yii::$app->request->isPost) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参

            $upload = new UploadsModel('file', "./uploads/goods/".yii::$app->session['uid']);
            $path = $upload->upload();
            $filePath = Yii::getAlias('@webroot/') . $path;

            $config = $this->getSystemConfig('ccvWPn', 'miniprogram');
            if ($config == false) {
                return result(500, "未配置小程序信息");
            }
            $miniProgram = Factory::miniProgram($config);
            $token = $miniProgram->access_token->getToken(true); // 强制重新从微信服务器获取 token
            $miniProgram['access_token']->setToken($token['access_token'], 7200);
            $url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token='.$token['access_token'].'&type=image';
            $data = array(
                'media'=>new \CURLFile($filePath),
            );
            $res = json_decode(curlPost($url, $data), true);

            if (!isset($res['errcode'])) {
                unlink($filePath);
                return result(200, "请求成功",['media_id'=>$res['media_id']]);
            } else {
                return result(500, $res['errmsg']);
            }
        } else {
            return result(500, "请求方式错误");
        }
    }

    //直播间导入商品
    public function actionImport(){
        if (yii::$app->request->isPost) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参

            $must = ['ids','roomid'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }

            $config = $this->getSystemConfig('ccvWPn', 'miniprogram');
            if ($config == false) {
                return result(500, "未配置小程序信息");
            }
            $miniProgram = Factory::miniProgram($config);
            $token = $miniProgram->access_token->getToken(true); // 强制重新从微信服务器获取 token
            $miniProgram['access_token']->setToken($token['access_token'], 7200);

            $url = 'https://api.weixin.qq.com/wxaapi/broadcast/room/addgoods?access_token='.$token['access_token'];

            $data = json_encode([
                'ids'=>$params['ids'],
                'roomId'=>$params['roomid'],
            ]);
            $res = json_decode(curlPostJson($url, $data), true);
            if ($res['errcode'] == 0) {
                return result(200, "请求成功");
            } else {
                return result(500, $res['errmsg']);
            }
        } else {
            return result(500, "请求方式错误");
        }
    }

    //商品列表
    public function actionGoodsList(){
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数

            $must = ['status','page','limit'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }

            //商品状态，0：未审核。1：审核中，2：审核通过，3：审核驳回
            $config = $this->getSystemConfig('ccvWPn', 'miniprogram');
            if ($config == false) {
                return result(500, "未配置小程序信息");
            }
            $miniProgram = Factory::miniProgram($config);
            $token = $miniProgram->access_token->getToken(true); // 强制重新从微信服务器获取 token
            $miniProgram['access_token']->setToken($token['access_token'], 7200);

            $params['page'] = $params['page']-1;
            $url = 'https://api.weixin.qq.com/wxaapi/broadcast/goods/getapproved?access_token='.$token['access_token'].'&status='.$params['status'].'&offset='.$params['page'].'&limit='.$params['limit'];

            $res = json_decode(curlGet($url), true);
            if ($res['errcode'] == 0){
                return ['status' => 200, 'message' => '请求成功', 'data' => $res['goods'], 'count' => $res['total']];
            } else {
                return result(500, $res['errmsg']);
            }

        } else {
            return result(500, "请求方式错误");
        }
    }

    //商品添加并提审
    public function actionGoodsAdd(){
        if (yii::$app->request->isPost) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参

            $must = ['id','img','name','price','price2','url'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }

            $config = $this->getSystemConfig('ccvWPn', 'miniprogram');
            if ($config == false) {
                return result(500, "未配置小程序信息");
            }
            $miniProgram = Factory::miniProgram($config);
            $token = $miniProgram->access_token->getToken(true); // 强制重新从微信服务器获取 token
            $miniProgram['access_token']->setToken($token['access_token'], 7200);

            $mediaId = $this->download($params['img'],$token['access_token']);
            if ($mediaId['status'] != 200) {
                return result(500, $mediaId['message']);
            }

            $url = 'https://api.weixin.qq.com/wxaapi/broadcast/goods/add?access_token='.$token['access_token'];

            $goodsData['goodsInfo'] = array(
                'coverImgUrl'=>$mediaId['data']['media_id'],
                'name'=>$params['name'],
                'priceType'=>3,
                'price'=>$params['price'],
                'price2'=>$params['price2'],
                'url'=>$params['url'],
            );
            $data = json_encode($goodsData);
            $res = json_decode(curlPostJson($url, $data), true);
            if ($res['errcode'] == 0) {
                //提交成功本地商品做标记
                $gooodsModel = new ShopGoodsModel();
                $goodsWhere['id'] = $params['id'];
                $gooodsModel->do_update($goodsWhere,['is_live_goods'=>1]);
                return result(200, "请求成功");
            } else {
                return result(500, $res['errmsg']);
            }
        } else {
            return result(500, "请求方式错误");
        }
    }

    //选择商品列表
    public function actionChoose(){
        if (yii::$app->request->isGet) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->get(); //获取地址栏参数

            $model = new ShopGoodsModel();
            if (isset($params['searchName'])) {
                if ($params['searchName'] != "") {
                    $where['or'] = ['or',['=','id', $params['searchName']],['like','name', $params['searchName']]];
                }
            }
            if (isset($params['page'])) {
                $where['page'] = $params['page'];
            }
            if (isset($params['limit'])) {
                $where['limit'] = $params['limit'];
            }
            $where['is_live_goods'] = 0;
            $array = $model->do_select($where);

            return $array;
        } else {
            return result(500, "请求方式错误");
        }
    }

    //删除小程序商品库商品
    public function actionGoodsDelete($id){
        if (yii::$app->request->isDelete) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参

            $must = ['goods_id'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }

            $config = $this->getSystemConfig('ccvWPn', 'miniprogram');
            if ($config == false) {
                return result(500, "未配置小程序信息");
            }
            $miniProgram = Factory::miniProgram($config);
            $token = $miniProgram->access_token->getToken(true); // 强制重新从微信服务器获取 token
            $miniProgram['access_token']->setToken($token['access_token'], 7200);

            $url = 'https://api.weixin.qq.com/wxaapi/broadcast/goods/delete?access_token='.$token['access_token'];
            $data = json_encode(['goodsId'=>$id]);
            $res = json_decode(curlPostJson($url, $data), true);
            if ($res['errcode'] == 0) {
                //提交成功本地商品做标记
                $gooodsModel = new ShopGoodsModel();
                $goodsWhere['id'] = $params['goods_id'];
                $gooodsModel->do_update($goodsWhere,['is_live_goods'=>0]);
                return result(200, "请求成功");
            } else {
                return result(500,$res['errmsg']);
            }
        } else {
            return result(500, "请求方式错误");
        }
    }

    //更新小程序商品库商品
    public function actionGoodsUpdate($id){
        if (yii::$app->request->isPut) {
            $request = yii::$app->request; //获取 request 对象
            $params = $request->bodyParams; //获取body传参

            //审核通过的商品仅允许更新价格类型与价格，审核中的商品不允许更新，未审核的商品允许更新所有字段，只传入需要更新的字段。
            $must = ['price','price2'];
            $rs = $this->checkInput($must, $params);
            if ($rs != false) {
                return $rs;
            }
            $config = $this->getSystemConfig('ccvWPn', 'miniprogram');
            if ($config == false) {
                return result(500, "未配置小程序信息");
            }
            $miniProgram = Factory::miniProgram($config);
            $token = $miniProgram->access_token->getToken(true); // 强制重新从微信服务器获取 token
            $miniProgram['access_token']->setToken($token['access_token'], 7200);

            $url = 'https://api.weixin.qq.com/wxaapi/broadcast/goods/update?access_token='.$token['access_token'];
            if ($params['price'] < $params['price2']) {
                return result(500, "现价不能高于原价");
            }
            $goodsData['goodsInfo'] = array(
                'priceType'=>3,
                'price'=>$params['price'],
                'price2'=>$params['price2'],
                'goodsId'=>$id,
            );
            $data = json_encode($goodsData);
            $res = json_decode(curlPostJson($url, $data), true);
            if ($res['errcode'] == 0) {
                return result(200, "请求成功");
            } else {
                return result(500, $res['errmsg']);
            }
        } else {
            return result(500, "请求方式错误");
        }
    }


}
